import type { IRole, IRoleParam, IRoleStatus } from "@/api/role";

import {
  getRoles as getRolesApi,
  addRole as addRoleApi,
  removeRole as removeRoleApi,
  updateRole as updateRoleApi
} from "@/api/role";

export type TRoleWithPage = IRole & IRoleParam;

export const useRoleStore = defineStore("role", () => {
  const store = reactive<IRoleStatus>({
    roles: [],
    count: 0
  });

  const getRoles = async (params: IRoleParam) => {
    const res = await getRolesApi(params);
    const { data } = res;

    store.roles = data.roles;
    store.count = data.count;
  };

  const addRole = async (params: TRoleWithPage) => {
    const { pageNum, pageSize, ...role } = params;
    const res = await addRoleApi(role);

    if (res) {
      getRoles({ pageNum, pageSize });
    }
  };

  const updateRole = async (params: TRoleWithPage) => {
    const { pageNum, pageSize, ...role } = params;
    const res = await updateRoleApi(role.id, role);

    if (res) {
      getRoles({ pageNum, pageSize });
    }
  };

  const removeRole = async (params: TRoleWithPage) => {
    const { pageNum, pageSize, id } = params;
    const res = await removeRoleApi(id);

    if (res) {
      getRoles({ pageNum, pageSize });
    }
  };

  return { getRoles, addRole, updateRole, removeRole, store };
});
